<template>
  <div class="home-container">
    <van-nav-bar>
      <template #title>
        <van-button class="search" icon="search" round size="small" to="/search">搜索</van-button>
      </template>
    </van-nav-bar>
    <van-tabs v-model="tabIndex">
      <van-tab v-for="item in channels" :title="item.name" :key="item.id">
<!--        文章列表-->
        <article-list :channel="item" />
<!--        文章列表-->
      </van-tab>
      <div slot="nav-right" @click="isPopupShow = true">
        <van-icon name="wap-nav" class="wap"/>
      </div>
      <div slot="nav-right">
        <div class="space"></div>
      </div>
    </van-tabs>
    <van-popup
      v-model="isPopupShow"
      round
      closeable
      close-icon-position="top-left"
      position="bottom"
      get-container="body"
      :style="{ height: '100%' }">
      <channel-edit
        :myChannels="channels"
        :activeIndex="tabIndex"
        @update-active = "tabIndex = $event"
        @closePopup = "isPopupShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { getUserChannels } from '../../api/user'
import ArticleList from '../../components/article-list.vue'
import ChannelEdit from '../../components/channel-edit'
import { getItem } from '../../utils/storage'
import { mapState } from 'vuex'

export default {
  name: 'homeIndex',
  components: {
    ArticleList,
    ChannelEdit
  },
  data () {
    return {
      channels: [],
      isPopupShow: false,
      tabIndex: 0
    }
  },
  methods: {
    async loadChannels () {
      let channels = []
      if (this.user) { // 已登录，请求在线数据
        const { data } = await getUserChannels()
        console.log('channels', data)
        channels = data.data.channels
      } else { // 没有登录
        const localChannels = getItem('user-channels')
        if (localChannels) { // 获取本地数据
          channels = localChannels
        } else { // 没有本地存储，请求默认列表数据
          const { data: { data: { channels: res } } } = await getUserChannels()
          channels = res
        }
      }
      this.channels = channels
    }
  },
  created () {
    this.loadChannels()
  },
  computed: mapState(['user']),
  watch: {
    user () { // 监听登录状态，切换本地、在线数据
      this.tabIndex = 0
      this.loadChannels()
    }
  }
}
</script>

<style scoped>
.search {
  color: #FFFFFF;
  border: none;
  width: 120px;
  background-color: rgba(255,255,255,0.2);
}
.search .van-nav-bar .van-icon {color: #FFFFFF;}
.wap {
  position: fixed;
  right: 0;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255,255,255,.9) url("../../assets/img/line.png") left center no-repeat;
}
.space {
  height: 44px;
  width: 44px;
  flex-shrink: 0;
}
</style>
